from django_redis import get_redis_connection
from . import meiduo_json
def merge_cart_cookie_to_redis(request, response):
#  取出ｃｏｏｋｉｅ中的数据
    user = request.user
    json_cart_dict = request.COOKIES.get('cart')
    if json_cart_dict == None:
        return response
    cart_dict = meiduo_json.loads(json_cart_dict)
    redis_conn = get_redis_connection('carts')
    redis_pl = redis_conn.pipeline()
    # hash user.id sku.id count {16: {'selected': False}, 11: {'selected': False}, 14: {'selected': False}}
    # 同步cookie中购物车数据
    for sku_id, sku_dict in cart_dict.items():
        redis_pl.hset('carts%d' % user.id, sku_id, sku_dict.get('count'))
    # selected 存set
        if sku_dict.get('selected'):
            redis_pl.sadd('selected%d' % user.id, sku_id)
        else:
            redis_pl.srem('selected%d' % user.id, sku_id)
    redis_pl.execute()
        # 清除cookie
    response.delete_cookie('cart')
    return response


